package ch.upndown.upndown.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import ch.upndown.upndown.R;

/**
 * Created by DonMiguel on 16.08.2014.
 */
public class IconAsyncTask extends AsyncTask<Void, Integer, Bitmap> {
    private ImageView imageView;
    private URL url;

    public IconAsyncTask(ImageView imageView, URL url) {
        this.imageView = imageView;
        this.url = url;
    }

    @Override
    protected Bitmap doInBackground(Void... params) {
        return downloadImage(url);
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        if (result != null) {
            imageView.setImageBitmap(result);
        } else {
            imageView.setImageResource(R.drawable.ic_launcher);
        }
    }


    private Bitmap downloadImage(URL url) {
        Bitmap bm = null;
        InputStream is = null;
        BufferedInputStream bis = null;
        try {
            URLConnection conn = url.openConnection();
            conn.connect();
            is = conn.getInputStream();
            bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
        } catch (IOException e) {
            Log.e("IconAsyncTask", e.getMessage().toString());
        } finally {
            try {
                is.close();
                bis.close();
            } catch (Exception e) {
            }
        }
        return bm;
    }
}